<template>
  <p
    class="break-words w-1/1 h-1/1"
    :class="props.vertical ? 'text-vertical' : ''"
    :style="{
      fontFamily: componentProps.fontFamily,
      fontSize: componentProps.fontSize + 'px',
      color: componentProps.fill
    }"
  >
    {{ componentProps.text }}
  </p>
</template>
<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, onBeforeUpdate, onUpdated } from 'vue';
import { useAutoDataBinding } from '@/composables/use-data-binding';
import { startComponentRender, endComponentRender } from '@/utils/performance-monitor';
import type { IDataBindingConfig } from '@/components/mt-edit/store/types';

const props = defineProps({
  // 数据绑定配置
  dataBinding: {
    type: Object as () => IDataBindingConfig,
    default: () => ({
      enabled: false,
      sourceId: '',
      dataPointId: '',
      targetProperty: 'text',
      transform: 'string',
      defaultValue: '',
      updateInterval: 0
    })
  },
  fontFamily: {
    type: String,
    default: ''
  },
  fontSize: {
    type: Number,
    default: 15
  },
  text: {
    type: String,
    default: ''
  },
  fill: {
    type: String,
    default: ''
  },
  vertical: {
    type: Boolean,
    default: false
  }
});

// 响应式属性对象（用于数据绑定）
const componentProps = ref({
  text: props.text,
  fontFamily: props.fontFamily,
  fontSize: props.fontSize,
  fill: props.fill,
  vertical: props.vertical
});

// 使用数据绑定
const shouldUseDataBinding =
  props.dataBinding && props.dataBinding.enabled && props.dataBinding.targetProperty !== 'hide';
const dataBinding = useAutoDataBinding(
  shouldUseDataBinding ? props.dataBinding : null,
  componentProps.value,
  (property: string, value: any) => {
    // 直接更新响应式对象的属性
    if (componentProps.value.hasOwnProperty(property)) {
      (componentProps.value as any)[property] = value;
    }
  }
);

// 监听 dataBinding 配置变化
// 性能监控
onMounted(() => {
  startComponentRender('text-vue', 'TextVue');
});

onBeforeUpdate(() => {
  startComponentRender('text-vue', 'TextVue');
});

onUpdated(() => {
  endComponentRender('text-vue', 'TextVue');
});

watch(
  () => props.dataBinding,
  (newConfig, oldConfig) => {
    // dataBinding配置变化处理
  },
  { deep: true }
);

// 监听props变化，同步到响应式属性对象
watch(
  () => props.text,
  (newValue) => {
    if (!props.dataBinding?.enabled) {
      componentProps.value.text = newValue;
    }
  }
);

watch(
  () => props.fontFamily,
  (newValue) => {
    componentProps.value.fontFamily = newValue;
  }
);

watch(
  () => props.fontSize,
  (newValue) => {
    componentProps.value.fontSize = newValue;
  }
);

watch(
  () => props.fill,
  (newValue) => {
    componentProps.value.fill = newValue;
  }
);

watch(
  () => props.vertical,
  (newValue) => {
    componentProps.value.vertical = newValue;
  }
);
</script>
<style scoped>
.text-vertical {
  writing-mode: tb;
  letter-spacing: 5px;
}
</style>
